<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="60%"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="所属分类" prop="cateId">
        <el-input placeholder="请选择分类" :value="current.name" type="text" readonly>
          <template slot="suffix">
            <el-button class="el-icon-edit" @click="checkSort" type="text">选择分类</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="题干内容" prop="info">
        <ck-editor ref="ckEditor" :change="contentChanged" />
        <!--<el-input v-model="dataForm.choiceqstInfo" placeholder="题干内容"></el-input>-->
      </el-form-item>
      <el-form-item label="选项" prop="option">
        <div>
          <div
            v-for="(item, index) in dataForm.option"
            style="display: flex;flex-direction: row;margin-bottom: 20px"
            :key="index"
          >
            <span style="white-space: nowrap;margin-right: 10px">{{item.key}}</span>
            <div>
              <div
                style="display: flex;flex-direction: row;align-content: center;align-items: center"
              >
                <el-input v-model="item.option" placeholder="选项"></el-input>
                <i
                  class="el-icon-delete"
                  v-if="dataForm.option.length > 2"
                  style="margin-left: 10px"
                  @click="removeOption(index)"
                ></i>
              </div>
            </div>
          </div>
          <el-button v-if="dataForm.option.length < 26" type="primary" @click="addOption">添加一个选项</el-button>
        </div>
      </el-form-item>
      <el-form-item label="答案" prop="answ">
        <el-checkbox-group v-model="dataForm.answ">
          <el-checkbox-button
            v-for="(item,index) in dataForm.option"
            :key="index"
            :label="item.key"
            border
          />
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="试题难度" prop="level">
        <el-radio-group v-model="dataForm.level">
          <el-radio :label="0">简单</el-radio>
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="2">困难</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="答案解析">
        <el-input type="textarea" v-model="dataForm.analysis" placeholder="答案解析"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :loading="loading">确定</el-button>
    </div>
    <!-- 分类管理 -->
    <el-dialog
      title="分类管理"
      :visible.sync="dialogFormVisible"
      :show-close="false"
      append-to-body
      width="30%"
    >
      <paper-cate
        ref="paperCate"
        v-if="paperCate"
        :setCurrent="setCurrent"
        :current="current"
        :url="{
                                update:'/exam-admin/ques/cate/update',
                                save:'/exam-admin/ques/cate/save',
                                delete:'/exam-admin/ques/cate/delete',
                                tree:'/exam-admin/ques/cate/tree'
                                }"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import paperCate from './../../../views/modules/paper/papercate'
import CkEditor from '../../../components/ckEditor/ckEditor'

export default {
  components: {
    CkEditor,
    paperCate
  },
  data() {
    let checkOptions = (rule, value, callback) => {
      value.forEach(x => {
        if (!x.option) {
          return callback(new Error(`${x.key}选项不能为空`))
        }
      })
      callback()
    }
    return {
      dialogFormVisible: false,
      current: {},
      paperCate: false,
      visible: false,
      loading: false,
      words: [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
      ],
      dataForm: {
        id: 0,
        cateId: '',
        info: '',
        option: [
          {
            key: 'A',
            option: ''
          },
          {
            key: 'B',
            option: ''
          }
        ],
        answ: [],
        level: 0,
        analysis: '',
        questype: 2
      },
      dataRule: {
        cateId: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
        info: [
          { required: true, message: '题干内容不能为空', trigger: 'blur' }
        ],
        option: [{ validator: checkOptions, trigger: 'blur' }],
        answ: [{ required: true, message: '答案不能为空', trigger: 'blur' }],
        level: [
          {
            required: true,
            message: '试题难度（0-简单，1-普通，2-困难）不能为空',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    contentChanged(content) {
      this.dataForm.info = content
    },
    setCurrent(data) {
      if (data.id) {
        this.current = data
        this.dataForm.cateId = data.id
        this.$nextTick(_ => this.$refs['dataForm'].validateField('cateId'))
      }
    },
    checkSort() {
      this.dialogFormVisible = true
      this.paperCate = true
      this.$nextTick(() => {
        this.$refs.paperCate.init()
      })
    },
    init(id) {
      this.current = {
        name: '',
        id: ''
      }
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(_ => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/exam-admin/ques/multi/info/${this.dataForm.id}`
            ),
            method: 'post',
            data: this.$http.adornParams()
          }).then(res => {
            if (res && res.code === 200) {
              let options = JSON.parse(res.data.options)
              this.dataForm.option = options.length
                ? JSON.parse(res.data.options)
                : []
              this.setCurrent({ name: res.data.cateName, id: res.data.cateId })
              this.$refs.ckEditor.setData(res.data.info)
              this.dataForm.info = res.data.info
              this.dataForm.answ = res.data.answ.split('')
              this.dataForm.level = res.data.level
              this.dataForm.analysis = res.data.analysis
            } else {
              this.dataForm.option = [
                {
                  key: 'A',
                  option: ''
                },
                {
                  key: 'B',
                  option: ''
                }
              ]
            }
          })
        } else {
          this.$refs.ckEditor.setData('')
          this.dataForm.info = ''
          this.dataForm.answ = []
          this.dataForm.level = 0
          this.dataForm.analysis = ''
          this.dataForm.option = [
            {
              key: 'A',
              option: ''
            },
            {
              key: 'B',
              option: ''
            }
          ]
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.loading = true
          this.$http({
            url: this.$http.adornUrl(
              `/exam-admin/ques/multi/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: {
              id: this.dataForm.id || undefined,
              cateId: this.dataForm.cateId,
              info: this.dataForm.info,
              options: JSON.stringify(
                this.dataForm.option.filter(x => x.option !== '')
              ),
              answ: this.dataForm.answ.join(''),
              analysis: this.dataForm.analysis,
              level: this.dataForm.level,
              quesType: this.dataForm.questype
            }
          }).then(data => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500
              })
              this.visible = false
              this.$emit('refreshDataList')
            } else {
              this.$message.warning(data.msg)
            }
            this.loading = false
          })
        }
      })
    },
    addOption() {
      if (this.dataForm.option.length >= 26) {
        return false
      }
      this.dataForm.option.push({
        key: this.words[this.dataForm.option.length],
        option: ''
      })
    },
    // 移除一个选项
    removeOption(index) {
      this.dataForm.answ = this.dataForm.answ.filter(
        x => x !== this.dataForm.option[index].key
      )
      this.dataForm.option.splice(index, 1)
      this.dataForm.option.forEach((x, i) => {
        x.key = this.words[i]
      })
      this.$nextTick(_ => this.$refs['dataForm'].validateField('option'))
    }
  }
}
</script>
